package cn.otrue.patienthealthmanager.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.HealthApplication;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.DrugListAdpater;
import cn.otrue.patienthealthmanager.bean.Alarm;
import cn.otrue.patienthealthmanager.bean.Alarm.DaysOfWeek;
import cn.otrue.patienthealthmanager.bean.AlarmModel;
import cn.otrue.patienthealthmanager.bean.Alarms;
import cn.otrue.patienthealthmanager.bean.DoctorBloodsugarTemplateMonitorPlan;
import cn.otrue.patienthealthmanager.bean.DoctorBloodsugarTemplateMonitorPlanModel;
import cn.otrue.patienthealthmanager.bean.DrugPlanModel;
import cn.otrue.patienthealthmanager.bean.DrugRemindModel;
import cn.otrue.patienthealthmanager.bean.PlusModel;
import cn.otrue.patienthealthmanager.bean.PressureRemindModel;
import cn.otrue.patienthealthmanager.bean.SugarTemplateMonitorDetail;
import cn.otrue.patienthealthmanager.bean.SugarTemplateMonitorPlanTime;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.db.DBTools;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.SwitchButton;
import cn.otrue.patienthealthmanager.view.WeekTable;

import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

/**
 * 主页->健康计划->健康计划
 * 
 * @author G
 * 
 */
public class HealthPlanActivity extends BaseActivity {

	private DoctorBloodsugarTemplateMonitorPlan plan = new DoctorBloodsugarTemplateMonitorPlan();
	private String bloodpressureId;
	private String bloodsugarId;
	private String drugplanId;
	private DrugListAdpater drugAdapter;
	private ListView lv_health_plan_druglist;
	private TextView tv_health_plan_adddrug;
	private TextView tv_health_plan_addplus;
	private TextView tv_plus_date;
	private TextView tv_plus_frequency;
	private TextView tv_plus_timelist;
	private TextView tv_plus_week;
	private WeekTable wt_health_plan_sugar;
	private LinearLayout ll_plus_all;
	private Spinner sp_health_plan_mod;
	private ArrayAdapter<String> adapter;
	private int type;
	private LinearLayout ll_drug_all;
	private TextView tv_plan_title;
	private TextView tv_plus_note;
	private String doctorId;
	private String doctorName;
	// 开始时间选择框
	private DatePickerDialog beginDateDialog;
	// 结束时间选择框
	private DatePickerDialog endDateDialog;
	// 开始时间
	private Calendar beginCalendar = Calendar.getInstance();
	// 结束时间
	private Calendar endCalendar = Calendar.getInstance();

	private List<DoctorBloodsugarTemplateMonitorPlanModel> planModelList;

	private EditText et_sugar_begin_time;
	private EditText et_sugar_end_time;
	private String bloodsugar_begintime;
	private String bloodsugar_endtime;
	private TextView tv_title_ot;
	private List<Alarm> alarmSugarList;
	private DbUtils dbUtils;
	private SimpleDateFormat sdf;
	private TextView tv_switch_plan;
	private SwitchButton sb_plan_setting_sugar;
	private SwitchButton sb_plan_setting_plus;
	private SwitchButton sb_plan_setting_drug;
	private LinearLayout ll_health_plan_sugar;
	private LinearLayout ll_health_plan_plus;
	private LinearLayout ll_health_plan_drug;
	private SharedPreferences mySharedPreferences;
	private AlertDialog mDialog;

	// ///////////////////////////////////////////////Handler/////////////////////////////////////////////////////
	/**
	 * 查询系统血糖模板(Handler)
	 */
	private Handler getMonitorListHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("Plan", dataStr);
				planModelList = HttpServer.gson
						.fromJson(
								dataStr,
								new TypeToken<List<DoctorBloodsugarTemplateMonitorPlanModel>>() {
								}.getType());

				for (int i = 0; i < planModelList.size(); i++) {
					Log.e("planmodel",
							HttpServer.gson.toJson(planModelList.get(i)));
				}

				String[] planModelArr = new String[planModelList.size() + 1];
				for (int i = 0; i < planModelList.size(); i++) {
					planModelArr[i] = planModelList.get(i)
							.getMonitortemplateName();

				}
				planModelArr[planModelList.size()] = "自定义模板";
				adapter = new ArrayAdapter<String>(HealthPlanActivity.this,
						android.R.layout.simple_list_item_1, planModelArr);
				sp_health_plan_mod.setAdapter(adapter);
				sp_health_plan_mod.setSelection(planModelList.size());
			} else {
				Toast.makeText(HealthPlanActivity.this, msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	/**
	 * 查询血糖计划(Handler)
	 */
	private Handler sugarHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("Plan", "sugarHandler" + dataStr);
				List<Object> list = HttpServer.gson.fromJson(dataStr,
						new TypeToken<List<Object>>() {
						}.getType());
				List<Map<String, String>> planList = HttpServer.gson.fromJson(
						HttpServer.gson.toJson(list.get(0)),
						new TypeToken<List<Map<String, String>>>() {
						}.getType());

				CommonUtil.null2Str(planList, "0");

				List<SugarTemplateMonitorDetail> sugarPlan = HttpServer.gson
						.fromJson(
								HttpServer.gson.toJson(planList),
								new TypeToken<List<SugarTemplateMonitorDetail>>() {
								}.getType());

				String sugarTimeStr = HttpServer.gson.toJson(list.get(1));
				Log.e("sugarTimeStr", sugarTimeStr);
				List<SugarTemplateMonitorPlanTime> sugarTime = HttpServer.gson
						.fromJson(
								sugarTimeStr,
								new TypeToken<List<SugarTemplateMonitorPlanTime>>() {
								}.getType());
				if (sugarTime != null && sugarTime.size() > 0) {
					if (!TextUtils.isEmpty(bloodsugar_begintime)
							&& !TextUtils.isEmpty(bloodsugar_endtime)) {
						et_sugar_begin_time.setText(bloodsugar_begintime
								.substring(0, 10));
						et_sugar_end_time.setText(bloodsugar_endtime.substring(
								0, 10));
						beginTime = bloodsugar_begintime.substring(0, 10);
						endTime = bloodsugar_endtime.substring(0, 10);
					}
					plan.setSugarPlanDetails(sugarPlan);
					plan.setSugarPlanTimeTemplate(sugarTime.get(0));
					wt_health_plan_sugar.changeData(plan.getSugarPlanDetails(),
							plan.getSugarPlanTimeTemplate());
				}
			} else {
				Toast.makeText(HealthPlanActivity.this, msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	/**
	 * 查询血压计划(Handler)
	 */
	private Handler plusHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {

				String dataStr = data.getString(HttpCons.DATA);
				Log.e("Plan", "plusHandler" + dataStr);
				List<Object> dataList = HttpServer.gson.fromJson(dataStr,
						new TypeToken<List<Object>>() {
						}.getType());

				List<PlusModel> plusPlan = HttpServer.gson.fromJson(
						HttpServer.gson.toJson(dataList.get(0)),
						new TypeToken<List<PlusModel>>() {
						}.getType());

				List<Map<String, Object>> plusTimeList = (List<Map<String, Object>>) dataList
						.get(1);
				List<String> week = new ArrayList<String>();

				for (int i = 0; i < plusTimeList.size(); i++) {
					week.add((int) Double.parseDouble(plusTimeList.get(i)
							.get("drugweek").toString().substring(0, 1))
							+ "");
				}
				if (!TextUtils.isEmpty(blood_pressure_note)) {
					plusPlan.get(0).setNote(blood_pressure_note);
				}
				plusPlan.get(0).setWeekList(week);
				plan.setPlusPressurePlanDetails(plusPlan.get(0));
				ll_plus_all.setVisibility(View.VISIBLE);

				changePlus();
			} else {
				Toast.makeText(HealthPlanActivity.this, msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	/**
	 * 查询用药计划(Handler)
	 */
	private Handler drugHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("Plan", "drugHandler" + dataStr);
				List<Map<String, Object>> list = HttpServer.gson.fromJson(
						dataStr, new TypeToken<List<Map<String, Object>>>() {
						}.getType());

				if (list != null && list.size() > 0) {
					List<DrugPlanModel> drugList = new ArrayList<DrugPlanModel>();
					for (int i = 0; i < list.size(); i++) {
						DrugPlanModel eachDrug = HttpServer.gson.fromJson(
								HttpServer.gson.toJson(list.get(i)),
								DrugPlanModel.class);

						List<Map<String, String>> drugTimeList = HttpServer.gson
								.fromJson(
										HttpServer.gson.toJson(list.get(i).get(
												"drugremindlist")),
										new TypeToken<List<Map<String, String>>>() {
										}.getType());

						List<String> week = new ArrayList<String>();

						for (int j = 0; j < drugTimeList.size(); j++) {
							String weekStr = drugTimeList.get(j)
									.get("drugweek");
							Log.e("weekStr", weekStr);
							week.add((int) Double.parseDouble(weekStr) + "");
						}

						eachDrug.setWeekList(week);
						drugList.add(eachDrug);

					}

					plan.getDrugModelList().clear();
					plan.getDrugModelList().addAll(drugList);
					drugAdapter.notifyDataSetChanged();
					ll_drug_all.setVisibility(View.VISIBLE);

				}
			} else {
				Toast.makeText(HealthPlanActivity.this, msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	/**
	 * 添加模板(Handler)
	 */
	public Handler addMonitorHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			DialogUtil.endProgressDialog(mDialog);
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("Plan", dataStr);
				Toast.makeText(HealthPlanActivity.this, "添加成功", 0).show();
				HealthPlanActivity.this.setResult(1002);
				HealthPlanActivity.this.finish();
			} else {
				Toast.makeText(HealthPlanActivity.this, msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			DialogUtil.endProgressDialog(mDialog);
			Toast.makeText(HealthPlanActivity.this, state, 0).show();
		}

	};

	// ////////////////////////////////////////////Handler_end/////////////////////////////////////////////////////////////////
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_health_plan);

		WindowManager wm = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		MyConst.width = wm.getDefaultDisplay().getWidth();// 屏幕宽度
		MyConst.height = wm.getDefaultDisplay().getHeight();

		dbUtils = DBTools.db;
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		mySharedPreferences = HealthApplication.getInstance()
				.getSharedPreferences("plan", Activity.MODE_PRIVATE);
		initView();
		getData();
	}

	private void initView() {
		initTitleBar();
		tv_plan_title = (TextView) findViewById(R.id.tv_plan_title);
		tv_health_plan_adddrug = (TextView) findViewById(R.id.tv_health_plan_adddrug);
		tv_health_plan_adddrug.setOnClickListener(this);

		wt_health_plan_sugar = (WeekTable) findViewById(R.id.wt_health_plan_sugar);
		wt_health_plan_sugar.changeView();
		tv_health_plan_addplus = (TextView) findViewById(R.id.tv_health_plan_addplus);
		tv_health_plan_addplus.setOnClickListener(this);

		et_sugar_begin_time = (EditText) findViewById(R.id.et_sugar_begin_time);
		et_sugar_end_time = (EditText) findViewById(R.id.et_sugar_end_time);

		tv_plus_date = (TextView) findViewById(R.id.tv_plus_date);
		tv_plus_frequency = (TextView) findViewById(R.id.tv_plus_frequency);
		tv_plus_timelist = (TextView) findViewById(R.id.tv_plus_timelist);
		tv_plus_week = (TextView) findViewById(R.id.tv_plus_week);
		tv_plus_note = (TextView) findViewById(R.id.tv_plus_note);
		ll_plus_all = (LinearLayout) findViewById(R.id.ll_plus_all);
		ll_drug_all = (LinearLayout) findViewById(R.id.ll_drug_all);
		ll_health_plan_sugar = (LinearLayout) findViewById(R.id.ll_health_plan_sugar);
		ll_health_plan_plus = (LinearLayout) findViewById(R.id.ll_health_plan_plus);
		ll_health_plan_drug = (LinearLayout) findViewById(R.id.ll_health_plan_drug);

		sp_health_plan_mod = (Spinner) findViewById(R.id.sp_health_plan_mod);
		lv_health_plan_druglist = (ListView) findViewById(R.id.lv_health_plan_druglist);
		tv_switch_plan = (TextView) findViewById(R.id.tv_switch_plan);
		tv_switch_plan.setOnClickListener(this);
		et_sugar_begin_time.setOnClickListener(this);
		et_sugar_end_time.setOnClickListener(this);

		ll_plus_all.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(HealthPlanActivity.this,
						PlusManagerActivity.class);
				intent.putExtra("type", type);
				intent.putExtra("data", HttpServer.gson.toJson(plan
						.getPlusPressurePlanDetails()));
				startActivityForResult(intent, 999);
			}
		});

		lv_health_plan_druglist
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						Intent intent = new Intent(HealthPlanActivity.this,
								DrugManagerActivity.class);
						intent.putExtra("type", type);

						intent.putExtra("data", HttpServer.gson.toJson(plan
								.getDrugModelList().get(arg2)));
						startActivityForResult(intent, arg2);
					}

				});

		sp_health_plan_mod
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						if (arg2 == planModelList.size()) {

							wt_health_plan_sugar.changeData(
									plan.getSugarPlanDetails(),
									plan.getSugarPlanTimeTemplate());
						} else {

							List<SugarTemplateMonitorPlanTime> timeList = planModelList
									.get(arg2)
									.getSugarTemplateMonitorPlanTimelist();
							List<SugarTemplateMonitorDetail> detailList = planModelList
									.get(arg2)
									.getSugarTemplateMonitorDetaillist();

							SugarTemplateMonitorPlanTime time;
							getInitPlan();
							if (timeList.size() <= 0) {
								time = getInitSugarTime();
							} else {
								time = timeList.get(0);
							}

							if (detailList.size() != 7) {
								detailList = getInitPlan();
							}
							plan.getSugarPlanDetails().clear();
							plan.getSugarPlanDetails().addAll(detailList);
							plan.setSugarPlanTimeTemplate(time);

							wt_health_plan_sugar.changeData(
									plan.getSugarPlanDetails(),
									plan.getSugarPlanTimeTemplate());
						}

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});

	}

	private void getData() {

		Intent intent = getIntent();
		type = intent.getIntExtra("type", 0);
		doctorId = intent.getStringExtra("doctorId");
		doctorName = intent.getStringExtra("doctorName");
		bloodsugarId = intent.getStringExtra("bloodsugarId");
		if (!TextUtils.isEmpty(bloodsugarId)) {
			bloodsugar_begintime = intent
					.getStringExtra("bloodsugar_begintime");
			bloodsugar_endtime = intent.getStringExtra("bloodsugar_endtime");
		}
		bloodpressureId = intent.getStringExtra("bloodpressureId");
		drugplanId = intent.getStringExtra("drugplanId");

		blood_pressure_note = intent.getStringExtra("blood_pressure_note");

		Log.e("Plan", "bloodsugarId:" + bloodsugarId + " bloodpressureId"
				+ bloodpressureId + " drugplanId" + drugplanId);

		if (doctorId!=null&&doctorId.equals(MyConst.getACCOUNT())) {
			type = MyConst.CHANGE_PLAN;
		} else {
			if (!TextUtils.isEmpty(doctorName)) {
				tv_plan_title.setText(doctorName);
			}
		}

		// 空白的血糖
		plan.setSugarPlanTimeTemplate(getInitSugarTime());
		plan.setSugarPlanDetails(getInitPlan());
		// 空白的血压
		PlusModel nullPlus = new PlusModel();
		nullPlus.setWeekList(new ArrayList<String>());
		plan.setPlusPressurePlanDetails(nullPlus);
		// 空白的用药

		plan.setDrugModelList(new ArrayList<DrugPlanModel>());

		switch (type) {
		case 0:
		case MyConst.BLANK_PLAN:
			// 得到系统模板
			getMonitorList();
			break;
		case MyConst.CHANGE_PLAN:
			// 得到系统模板
			getMonitorList();
			getAllPlan(bloodsugarId, bloodpressureId, drugplanId);
			break;
		case MyConst.SHOW_PLAN:
			tv_switch_plan.setVisibility(View.GONE);
			et_sugar_begin_time.setOnClickListener(null);
			et_sugar_end_time.setOnClickListener(null);
			sp_health_plan_mod.setVisibility(View.GONE);
			tv_health_plan_addplus.setVisibility(View.GONE);
			tv_health_plan_adddrug.setVisibility(View.GONE);
			tv_title_ot.setVisibility(View.GONE);
			getAllPlan(bloodsugarId, bloodpressureId, drugplanId);
			break;
		default:
			break;
		}

		drugAdapter = new DrugListAdpater(this, plan.getDrugModelList());
		lv_health_plan_druglist.setAdapter(drugAdapter);
		wt_health_plan_sugar.changeData(plan.getSugarPlanDetails(),
				plan.getSugarPlanTimeTemplate());

	}

	/**
	 * 得到系统模板
	 */
	private void getMonitorList() {
		TransferParameter parameter = new TransferParameter();

		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("doctorId", MyConst.SYSTEM_MONITOR);
		parameter.setData(data);
		new HttpServer().post(
				HttpCons.QUERY_DOCTOR_BLOOD_SUGAR_TEMPLATE_MONITOR_PLANLIST,
				parameter, getMonitorListHandler);

	}

	/**
	 * 得到全部计划
	 */
	public void getAllPlan(String bloodsugarId, String bloodpressureId,
			String drugplanId) {

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		// 血糖计划
		if (!TextUtils.isEmpty(bloodsugarId)) {
			getBloodsugar(bloodsugarId);
			editor.putInt("sugar", 1);
			ll_health_plan_sugar.setVisibility(View.VISIBLE);

		} else {
			editor.putInt("sugar", 0);
			ll_health_plan_sugar.setVisibility(View.GONE);
		}

		// 血压计划
		if (!TextUtils.isEmpty(bloodpressureId)) {
			getBloodpressure(bloodpressureId);
			editor.putInt("plus", 1);
			ll_health_plan_plus.setVisibility(View.VISIBLE);
		} else {
			editor.putInt("plus", 0);
			ll_health_plan_plus.setVisibility(View.GONE);
		}

		// 用药
		if (!TextUtils.isEmpty(drugplanId)) {
			getDrugplan(drugplanId);
			editor.putInt("drug", 1);
			ll_health_plan_drug.setVisibility(View.VISIBLE);
		} else {
			editor.putInt("drug", 0);
			ll_health_plan_drug.setVisibility(View.GONE);
		}
		editor.commit();

	}

	/**
	 * 通过血糖id得到血糖计划
	 * 
	 * @param bloodsugarId
	 */
	private void getBloodsugar(String bloodsugarId) {
		TransferParameter parameter = new TransferParameter();
		parameter.setPagesize("20");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("bloodsugarplanId", bloodsugarId);
		parameter.setData(data);

		new HttpServer().post(
				HttpCons.QUERYPATIENT_RUN_MONITOR_BLOODSUGAR_PLAN, parameter,
				sugarHandler);
	}

	/**
	 * 通过血压id得到血糖计划
	 * 
	 * @param bloodpressureId
	 */
	private void getBloodpressure(String bloodpressureId) {
		TransferParameter parameter = new TransferParameter();
		parameter.setPagesize("20");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("bloodpressureid", bloodpressureId);
		parameter.setData(data);
		new HttpServer().post(
				HttpCons.QUERYPATIENT_RUN_MONITOR_BLOODPRESSURE_PLAN,
				parameter, plusHandler);
	}

	/**
	 * 得到初始血糖时间模板
	 * 
	 * @return
	 */
	private SugarTemplateMonitorPlanTime getInitSugarTime() {
		SugarTemplateMonitorPlanTime planTime = new SugarTemplateMonitorPlanTime();
		planTime.setBefore_dawn("03:00");
		planTime.setEmpty_stomach("06:30");
		planTime.setAfter_breakfast("09:00");
		planTime.setBefore_lunch("11:30");
		planTime.setAfter_lunch("14:00");
		planTime.setBefore_dinner("17:30");
		planTime.setAfter_dinner("20:00");
		planTime.setBefore_sleep("22:00");
		return planTime;
	}

	/**
	 * 得到初始化计划列表
	 */

	public List<SugarTemplateMonitorDetail> getInitPlan() {
		List<SugarTemplateMonitorDetail> planData = new ArrayList<SugarTemplateMonitorDetail>();
		for (int j = 0; j < 7; j++) {
			SugarTemplateMonitorDetail detail = new SugarTemplateMonitorDetail();
			detail.setWeekend(j + 1);
			detail.setBefore_drawn(0);
			detail.setEmpty_stomach(0);
			detail.setAfter_breakfast(0);
			detail.setBefore_lunch(0);
			detail.setAfter_lunch(0);
			detail.setBefore_dinner(0);
			detail.setAfter_dinner(0);
			detail.setBefore_sleep(0);
			planData.add(detail);
		}
		return planData;
	}

	private void getDrugplan(String drugplanId) {
		TransferParameter parameter = new TransferParameter();
		parameter.setPagesize("20");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("drugplanId", drugplanId);
		parameter.setData(data);

		new HttpServer().post(HttpCons.QUERYPATIENT_RUN_MONITOR_DRUG_PLAN,
				parameter, drugHandler);
	}

	private void initTitleBar() {
		TextView tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		TextView tv_title_title = (TextView) findViewById(R.id.tv_title_title);
		tv_title_ot = (TextView) findViewById(R.id.tv_title_ot);

		tv_title_back.setVisibility(View.VISIBLE);
		tv_title_back.setOnClickListener(this);

		tv_title_title.setText(getString(R.string.health_plan));

		tv_title_ot.setVisibility(View.VISIBLE);
		tv_title_ot.setOnClickListener(this);

	}

	private AlertDialog setDialog;

	@Override
	public void onClick(View arg0) {
		Intent intent = new Intent();
		switch (arg0.getId()) {

		case R.id.tv_title_back:
			finish();
			break;
		case R.id.tv_title_ot:
			try {
				addAllPlan();
			} catch (Exception e) {
				DialogUtil.endProgressDialog(mDialog);
				Toast.makeText(HealthPlanActivity.this, "数据错误", 0).show();
			}
			break;
		case R.id.tv_health_plan_adddrug:
			intent.setClass(this, DrugManagerActivity.class);
			intent.putExtra("type", type);
			startActivityForResult(intent, 999);
			break;
		case R.id.tv_health_plan_addplus:
			intent.setClass(this, PlusManagerActivity.class);
			intent.putExtra("type", type);
			startActivityForResult(intent, 999);
			break;
		case R.id.et_sugar_begin_time:

			beginDateDialog = new DatePickerDialog(this, BeginDateSet,
					beginCalendar.get(Calendar.YEAR),
					beginCalendar.get(Calendar.MONTH),
					beginCalendar.get(Calendar.DAY_OF_MONTH));
			beginDateDialog.setTitle("开始时间");
			beginDateDialog.show();

			break;
		case R.id.et_sugar_end_time:
			endDateDialog = new DatePickerDialog(this, EndDateSet,
					endCalendar.get(Calendar.YEAR),
					endCalendar.get(Calendar.MONTH),
					endCalendar.get(Calendar.DAY_OF_MONTH));
			endDateDialog.setTitle("结束时间");
			endDateDialog.show();
			break;
		case R.id.tv_switch_plan:
			View dialogView = initSettingDialogView(
					R.layout.dialog_plan_setting, new SettingClicklistener());
			if (null != dialogView) {
				setDialog = DialogUtil.showDialog(this, dialogView, true);
			}
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		Log.e("plan", "onDestroy");
		mySharedPreferences.edit().clear().commit();

		super.onDestroy();
	}

	private View initSettingDialogView(int layoutId,
			SettingClicklistener settingClicklistener) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(layoutId, null);
		sb_plan_setting_sugar = (SwitchButton) view
				.findViewById(R.id.sb_plan_setting_sugar);
		sb_plan_setting_plus = (SwitchButton) view
				.findViewById(R.id.sb_plan_setting_plus);
		sb_plan_setting_drug = (SwitchButton) view
				.findViewById(R.id.sb_plan_setting_drug);

		int sugar = mySharedPreferences.getInt("sugar", 1);
		int plus = mySharedPreferences.getInt("plus", 1);
		int drug = mySharedPreferences.getInt("drug", 1);
		if (sugar != 1) {
			sb_plan_setting_sugar.changeOpen();
		}
		if (plus != 1) {
			sb_plan_setting_plus.changeOpen();
		}
		if (drug != 1) {
			sb_plan_setting_drug.changeOpen();
		}
		sb_plan_setting_sugar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				sb_plan_setting_sugar.changeOpen();
			}
		});
		sb_plan_setting_plus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				sb_plan_setting_plus.changeOpen();
			}
		});
		sb_plan_setting_drug.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				sb_plan_setting_drug.changeOpen();
			}
		});
		TextView leftBtn = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		leftBtn.setOnClickListener(settingClicklistener);
		TextView rightBtn = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		rightBtn.setOnClickListener(settingClicklistener);

		return view;
	}

	private void changePlanView() {

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		if (sb_plan_setting_sugar.open) {
			editor.putInt("sugar", 1);
			ll_health_plan_sugar.setVisibility(View.VISIBLE);
		} else {
			editor.putInt("sugar", 0);
			ll_health_plan_sugar.setVisibility(View.GONE);
		}
		if (sb_plan_setting_plus.open) {
			editor.putInt("plus", 1);
			ll_health_plan_plus.setVisibility(View.VISIBLE);
		} else {
			editor.putInt("plus", 0);
			ll_health_plan_plus.setVisibility(View.GONE);
		}
		if (sb_plan_setting_drug.open) {
			editor.putInt("drug", 1);
			ll_health_plan_drug.setVisibility(View.VISIBLE);
		} else {
			editor.putInt("drug", 0);
			ll_health_plan_drug.setVisibility(View.GONE);
		}
		editor.commit();
	}

	/**
	 * 页面设置的监听
	 * 
	 * @author g
	 * 
	 */
	private class SettingClicklistener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				setDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定
				if (sb_plan_setting_sugar.open || sb_plan_setting_plus.open
						|| sb_plan_setting_drug.open) {
					changePlanView();
					setDialog.dismiss();
				} else {
					Toast.makeText(HealthPlanActivity.this, "请至少选择一项计划", 0)
							.show();
				}
				break;
			}

		}
	}

	/**
	 * 添加模板
	 * 
	 * @param view
	 */
	public void add() {
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("monitortemplateName", "模板A");
		data.put("monitortemplateIntroduce", "这是模板1");

		List<Map<String, SugarTemplateMonitorPlanTime>> timeList = new ArrayList<Map<String, SugarTemplateMonitorPlanTime>>();
		Map<String, SugarTemplateMonitorPlanTime> eachTime = new HashMap<String, SugarTemplateMonitorPlanTime>();
		eachTime.put("SugarTemplateMonitorPlanTime",
				wt_health_plan_sugar.getTimeData());

		timeList.add(eachTime);

		List<Map<String, SugarTemplateMonitorDetail>> planList = new ArrayList<Map<String, SugarTemplateMonitorDetail>>();

		for (int i = 0; i < wt_health_plan_sugar.getDetailData().size(); i++) {
			Map<String, SugarTemplateMonitorDetail> eachPlan = new HashMap<String, SugarTemplateMonitorDetail>();
			eachPlan.put("SugarTemplateMonitorDetail", wt_health_plan_sugar
					.getDetailData().get(i));
			planList.add(eachPlan);
		}

		data.put("TemplatePlanTime", timeList);
		data.put("TemplateDetail", planList);

		parameter.setData(data);

		new HttpServer().post(
				HttpCons.INSERT_DOCTOR_BLOODSUGAR_TEMPLATE_MONITOR_PLAN,
				parameter, addMonitorHandler);
	}

	/**
	 * 添加全部计划
	 * 
	 * @throws DbException
	 * @throws ParseException
	 */
	public void addAllPlan() throws DbException, ParseException {
		mDialog = DialogUtil.startProgressDialog(this, "计划修改中...");
		TransferParameter parameter = new TransferParameter();
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("doctorId", doctorId);
		data.put("patientId", MyConst.getACCOUNT());

		// 血糖计划
		List<Map<String, SugarTemplateMonitorDetail>> sugarList = new ArrayList<Map<String, SugarTemplateMonitorDetail>>();
		// 血糖时间
		List<Map<String, SugarTemplateMonitorPlanTime>> timeList = new ArrayList<Map<String, SugarTemplateMonitorPlanTime>>();
		// 用药计划
		List<Map<String, DrugPlanModel>> drugList = new ArrayList<Map<String, DrugPlanModel>>();
		List<Map<String, DrugRemindModel>> drugTime = new ArrayList<Map<String, DrugRemindModel>>();
		// 血压计划
		List<Map<String, PlusModel>> plusList = new ArrayList<Map<String, PlusModel>>();
		List<Map<String, PressureRemindModel>> plusTime = new ArrayList<Map<String, PressureRemindModel>>();

		int sugar = mySharedPreferences.getInt("sugar", -1);
		int plus = mySharedPreferences.getInt("plus", -1);
		int drug = mySharedPreferences.getInt("drug", -1);

		if (sugar == 1) {
			if (!TextUtils.isEmpty(beginTime) && !TextUtils.isEmpty(endTime)) {
				Map<String, SugarTemplateMonitorPlanTime> eachTime = new HashMap<String, SugarTemplateMonitorPlanTime>();
				eachTime.put("SugarMonitorPlanTime",
						wt_health_plan_sugar.getTimeData());
				timeList.add(eachTime);

				for (int i = 0; i < wt_health_plan_sugar.getDetailData().size(); i++) {
					Map<String, SugarTemplateMonitorDetail> eachList = new HashMap<String, SugarTemplateMonitorDetail>();
					eachList.put("PatientRunMonitorBloodsugarPlan",
							wt_health_plan_sugar.getDetailData().get(i));

					sugarList.add(eachList);
				}
				// 血糖计划
				data.put("bloodsugarlist", sugarList);
				// 血糖时间
				data.put("sugartime", timeList);
				// 血糖开始时间
				data.put("bloodsugar_begintime", beginTime);
				// 血糖结束时间
				data.put("bloodsugar_endtime", endTime);

				// 添加血糖闹钟
				saveSugarAlarmData();
			} else {
				DialogUtil.endProgressDialog(mDialog);
				Toast.makeText(this, "请选择血糖计划的开始和结束时间", 0).show();
				return;
			}
		} else {
			// 血糖计划
			data.put("bloodsugarlist", sugarList);
			// 血糖时间
			data.put("sugartime", timeList);
			// 血糖开始时间
			data.put("bloodsugar_begintime", null);
			// 血糖结束时间
			data.put("bloodsugar_endtime", null);

		}
		if (plus == 1) {
			if (!TextUtils.isEmpty(plan.getPlusPressurePlanDetails()
					.getPlan_begintime())) {
				Map<String, PlusModel> plusMap = new HashMap<String, PlusModel>();

				plusMap.put("PatientRunMonitorBloodpressurePlan",
						plan.getPlusPressurePlanDetails());
				plusList.add(plusMap);
				List<String> eachPlusTime = plan.getPlusPressurePlanDetails()
						.getWeekList();
				for (int j = 0; j < eachPlusTime.size(); j++) {
					Map<String, PressureRemindModel> eachDrugTimeMap = new HashMap<String, PressureRemindModel>();
					PressureRemindModel eachplusTime = new PressureRemindModel();
					eachplusTime.setDrugweek(Integer.parseInt(eachPlusTime
							.get(j)));
					eachDrugTimeMap.put("PressRemind", eachplusTime);
					plusTime.add(eachDrugTimeMap);
				}

				// 血压计划
				data.put("bloodpresslist", plusList);
				// 血压提醒
				data.put("bloodpressremindlist", plusTime);
				// 血压开始时间
				data.put("bloodpressure_begintime", plan
						.getPlusPressurePlanDetails().getPlan_begintime());
				// 血压结束时间
				data.put("bloodpressure_endtime", plan
						.getPlusPressurePlanDetails().getPlan_endtime());
				// 血压备注
				data.put("blood_pressure_note", plan
						.getPlusPressurePlanDetails().getNote());
				// 添加血压闹钟
				savePlusAlarmData();
			} else {
				DialogUtil.endProgressDialog(mDialog);
				Toast.makeText(this, "请添加血压计划详情", 0).show();
				return;
			}
		} else {
			// 血压计划
			data.put("bloodpresslist", plusList);
			// 血压提醒
			data.put("bloodpressremindlist", plusTime);
			// 血压开始时间
			data.put("bloodpressure_begintime", null);
			// 血压结束时间
			data.put("bloodpressure_endtime", null);
			// 血压备注
			data.put("blood_pressure_note", null);
		}
		if (drug == 1) {
			if (plan.getDrugModelList().size() > 0) {
				for (int i = 0; i < plan.getDrugModelList().size(); i++) {

					DrugPlanModel eachDrug = plan.getDrugModelList().get(i);

					Map<String, DrugPlanModel> eachMap = new HashMap<String, DrugPlanModel>();
					eachMap.put("PatientRunMonitorDrugPlan", eachDrug);
					drugList.add(eachMap);

					List<String> eachDrugTime = eachDrug.getWeekList();
					for (int j = 0; j < eachDrugTime.size(); j++) {
						Map<String, DrugRemindModel> eachDrugTimeMap = new HashMap<String, DrugRemindModel>();
						DrugRemindModel eachdrugTime = new DrugRemindModel();
						eachdrugTime.setDrugid(eachDrug.getDrugid());
						eachdrugTime.setDrugweek(Integer.parseInt(eachDrugTime
								.get(j)));
						eachDrugTimeMap.put("DrugRemind", eachdrugTime);
						drugTime.add(eachDrugTimeMap);
					}
				}

				// 用药计划
				data.put("druglist", drugList);
				// 用药提醒
				data.put("drugremindlist", drugTime);
				List<String> dateList = getMinDate();
				// 用药开始时间
				data.put("drugplan_begintime", dateList.get(0));
				// 用药结束时间
				data.put("drugplan_endtime", dateList.get(1));
				// 保存用药闹钟
				saveDrugAlarmData();
			} else {
				DialogUtil.endProgressDialog(mDialog);
				Toast.makeText(this, "请添加用药计划详情", 0).show();
				return;
			}
		} else {
			// 用药计划
			data.put("druglist", drugList);
			// 用药提醒
			data.put("drugremindlist", drugTime);

			data.put("drugplan_begintime", null);
			// 用药结束时间
			data.put("drugplan_endtime", null);
		}

		if ((sugar == 1) || (plus == 1) || (drug == 1)) {

			// 血糖id
			data.put("bloodsugarId", bloodsugarId);
			// 血压id
			data.put("bloodpressureId", bloodpressureId);
			// 用药id
			data.put("drugplanId", drugplanId);
			data.put("state", MyConst.OFF_PLAN);
			parameter.setData(data);
			Log.e("Plan", HttpServer.gson.toJson(parameter));
			if (!TextUtils.isEmpty(bloodsugarId)
					|| !TextUtils.isEmpty(bloodpressureId)
					|| !TextUtils.isEmpty(drugplanId)) {
				new HttpServer().post(HttpCons.UPDATET_PLAN, parameter,
						addMonitorHandler);
			} else {
				new HttpServer().post(HttpCons.INSERT_PLAN, parameter,
						addMonitorHandler);
			}
		} else {
			DialogUtil.endProgressDialog(mDialog);
			Toast.makeText(HealthPlanActivity.this, "请至少选择一项计划", 0).show();
		}

	}

	/**
	 * 根据id删除计划的所有Alarm
	 * 
	 * @param id
	 *            患者id
	 * @param did
	 *            医生id
	 * @param type
	 *            计划类型
	 * @throws DbException
	 */
	public void deleteAllAlarmById(String id, String did, int type)
			throws DbException {
		List<AlarmModel> oldAlarm = dbUtils.findAll(Selector
				.from(AlarmModel.class).where("id", "=", id)
				.and(WhereBuilder.b("did", "=", did))
				.and(WhereBuilder.b("type", "=", type)));
		if (oldAlarm != null) {
			for (int z = 0; z < oldAlarm.size(); z++) {
				String alarmIdStr = oldAlarm.get(z).getAlarmAlarmStr();
				if (!TextUtils.isEmpty(alarmIdStr)) {
					List<String> idList = HttpServer.gson.fromJson(alarmIdStr,
							new TypeToken<List<String>>() {
							}.getType());
					for (int i = 0; i < idList.size(); i++) {
						Alarms.deleteAlarm(this,
								Integer.parseInt(idList.get(i)));
					}
				}
				dbUtils.delete(oldAlarm.get(z));
			}

		}
	}

	/**
	 * 保存血糖闹钟
	 * 
	 * @throws DbException
	 */
	public void saveSugarAlarmData() throws DbException {
		deleteAllAlarmById(MyConst.getACCOUNT(), MyConst.getACCOUNT(),
				MyConst.SUGAR);

		List<String> before_drawnMap = new ArrayList<String>();
		List<String> empty_stomachMap = new ArrayList<String>();
		List<String> after_breakfastMap = new ArrayList<String>();
		List<String> before_lunchMap = new ArrayList<String>();
		List<String> after_lunchMap = new ArrayList<String>();
		List<String> before_dinnerMap = new ArrayList<String>();
		List<String> after_dinnerMap = new ArrayList<String>();
		List<String> before_sleepMap = new ArrayList<String>();
		for (int i = 0; i < plan.getSugarPlanDetails().size(); i++) {
			SugarTemplateMonitorDetail detail = plan.getSugarPlanDetails().get(
					i);

			if (isColock(detail.getBefore_drawn())) {
				before_drawnMap.add(i + "");

			}
			if (isColock(detail.getEmpty_stomach())) {
				empty_stomachMap.add(i + "");

			}
			if (isColock(detail.getAfter_breakfast())) {
				after_breakfastMap.add(i + "");

			}
			if (isColock(detail.getBefore_lunch())) {
				before_lunchMap.add(i + "");

			}
			if (isColock(detail.getAfter_lunch())) {
				after_lunchMap.add(i + "");

			}
			if (isColock(detail.getBefore_dinner())) {
				before_dinnerMap.add(i + "");

			}
			if (isColock(detail.getAfter_dinner())) {
				after_dinnerMap.add(i + "");

			}
			if (isColock(detail.getBefore_sleep())) {
				before_sleepMap.add(i + "");

			}
		}

		String before_dawn = plan.getSugarPlanTimeTemplate().getBefore_dawn();
		String empty_stomach = plan.getSugarPlanTimeTemplate()
				.getEmpty_stomach();
		String after_breakfast = plan.getSugarPlanTimeTemplate()
				.getAfter_breakfast();
		String before_lunch = plan.getSugarPlanTimeTemplate().getBefore_lunch();
		String after_lunch = plan.getSugarPlanTimeTemplate().getAfter_lunch();
		String before_dinner = plan.getSugarPlanTimeTemplate()
				.getBefore_dinner();
		String after_dinner = plan.getSugarPlanTimeTemplate().getAfter_dinner();
		String before_sleep = plan.getSugarPlanTimeTemplate().getBefore_sleep();

		alarmSugarList = new ArrayList<Alarm>();
		alarmSugarList.add(getSugarAlarmByData(before_dawn, before_drawnMap));
		alarmSugarList
				.add(getSugarAlarmByData(empty_stomach, empty_stomachMap));
		alarmSugarList.add(getSugarAlarmByData(after_breakfast,
				after_breakfastMap));
		alarmSugarList.add(getSugarAlarmByData(before_lunch, before_lunchMap));
		alarmSugarList.add(getSugarAlarmByData(after_lunch, after_lunchMap));
		alarmSugarList
				.add(getSugarAlarmByData(before_dinner, before_dinnerMap));
		alarmSugarList.add(getSugarAlarmByData(after_dinner, after_dinnerMap));
		alarmSugarList.add(getSugarAlarmByData(before_sleep, before_sleepMap));
		for (int j = 0; j < alarmSugarList.size(); j++) {
			Alarms.addAlarm(this, alarmSugarList.get(j));
		}

		List<String> alarmIdList = new ArrayList<String>();
		for (int i = 0; i < alarmSugarList.size(); i++) {
			alarmIdList.add(alarmSugarList.get(i).id + "");
		}
		AlarmModel alarmModel = new AlarmModel();
		alarmModel.setId(MyConst.getACCOUNT());
		alarmModel.setDid(MyConst.getACCOUNT());
		alarmModel.setType(MyConst.SUGAR);
		alarmModel.setAlarmAlarmStr(HttpServer.gson.toJson(alarmIdList));
		alarmModel.setBeginTime(beginCalendar.getTime());
		alarmModel.setEndTime(endCalendar.getTime());

		dbUtils.save(alarmModel);

	}

	/**
	 * 保存血压闹钟
	 * 
	 * @throws ParseException
	 * @throws DbException
	 */
	public void savePlusAlarmData() throws ParseException, DbException {
		deleteAllAlarmById(MyConst.getACCOUNT(), MyConst.getACCOUNT(),
				MyConst.PLUS_PRESSURE);
		List<Alarm> plusAlarmList = new ArrayList<Alarm>();
		PlusModel plusModel = plan.getPlusPressurePlanDetails();

		// 整体的week
		DaysOfWeek dow = new DaysOfWeek(0);
		dow.set(0, false);
		dow.set(1, false);
		dow.set(2, false);
		dow.set(3, false);
		dow.set(4, false);
		dow.set(5, false);
		dow.set(6, false);
		for (int i = 0; i < plusModel.getWeekList().size(); i++) {
			dow.set(Integer.parseInt(plusModel.getWeekList().get(i)), true);
		}

		boolean enabled = true;
		boolean vibrate = true;

		String plusTimeStr = plusModel.getMesuretime();
		String[] timearr = plusTimeStr.split("  ");
		for (int i = 0; i < timearr.length; i++) {
			String[] timeArr = timearr[i].split(":");
			int hour = Integer.parseInt(timeArr[0]);
			int minutes = Integer.parseInt(timeArr[1]);
			plusAlarmList.add(getInitAlarm(-1, enabled, hour, minutes, dow,
					vibrate, "测血压啦"));
		}

		for (int j = 0; j < plusAlarmList.size(); j++) {
			Alarms.addAlarm(this, plusAlarmList.get(j));
		}

		List<String> alarmIdList = new ArrayList<String>();
		for (int i = 0; i < plusAlarmList.size(); i++) {
			alarmIdList.add(plusAlarmList.get(i).id + "");
		}
		AlarmModel alarmModel = new AlarmModel();
		alarmModel.setId(MyConst.getACCOUNT());
		alarmModel.setDid(MyConst.getACCOUNT());
		alarmModel.setType(MyConst.PLUS_PRESSURE);
		alarmModel.setAlarmAlarmStr(HttpServer.gson.toJson(alarmIdList));
		alarmModel.setBeginTime(sdf.parse(plan.getPlusPressurePlanDetails()
				.getPlan_begintime()));
		alarmModel.setEndTime(sdf.parse(plan.getPlusPressurePlanDetails()
				.getPlan_begintime()));

		dbUtils.save(alarmModel);

	}

	/**
	 * 保存用药闹钟
	 * 
	 * @throws ParseException
	 * @throws DbException
	 */
	public void saveDrugAlarmData() throws ParseException, DbException {
		deleteAllAlarmById(MyConst.getACCOUNT(), MyConst.getACCOUNT(),
				MyConst.DRUG);
		// 全部的用药计划
		List<DrugPlanModel> allDrugPlan = plan.getDrugModelList();

		for (int z = 0; z < allDrugPlan.size(); z++) {
			// 整体的用药计划
			List<Alarm> drugAlarmList = new ArrayList<Alarm>();

			DrugPlanModel drugModel = allDrugPlan.get(z);
			// 整体的week
			DaysOfWeek dow = new DaysOfWeek(0);
			dow.set(0, false);
			dow.set(1, false);
			dow.set(2, false);
			dow.set(3, false);
			dow.set(4, false);
			dow.set(5, false);
			dow.set(6, false);
			for (int i = 0; i < drugModel.getWeekList().size(); i++) {
				dow.set(Integer.parseInt(drugModel.getWeekList().get(i)), true);
			}
			boolean enabled = true;
			boolean vibrate = true;
			String breakfast = drugModel.getBreakfast();
			String drugfrequency = drugModel.getDrugfrequency();

			String[] timearr = getDrugTime(breakfast, drugfrequency);
			for (int i = 0; i < timearr.length; i++) {
				String[] timeArr = timearr[i].split(":");
				int hour = Integer.parseInt(timeArr[0]);
				int minutes = Integer.parseInt(timeArr[1]);
				drugAlarmList.add(getInitAlarm(-1, enabled, hour, minutes, dow,
						vibrate, "该吃" + drugModel.getDrugName() + "药了   剂量是"
								+ drugModel.getDrugdose()));
			}

			for (int j = 0; j < drugAlarmList.size(); j++) {
				Alarms.addAlarm(this, drugAlarmList.get(j));
			}

			List<String> alarmIdList = new ArrayList<String>();
			for (int i = 0; i < drugAlarmList.size(); i++) {
				alarmIdList.add(drugAlarmList.get(i).id + "");
			}
			AlarmModel alarmModel = new AlarmModel();
			alarmModel.setId(MyConst.getACCOUNT());
			alarmModel.setDid(MyConst.getACCOUNT());
			alarmModel.setType(MyConst.DRUG);
			alarmModel.setAlarmAlarmStr(HttpServer.gson.toJson(alarmIdList));
			alarmModel.setBeginTime(sdf.parse(drugModel.getDrugbegintime()));
			alarmModel.setEndTime(sdf.parse(drugModel.getDrugendtime()));
			dbUtils.save(alarmModel);

		}

	}

	/**
	 * 吃药时间
	 */
	final static String[] breakfastArr = { "餐前", "餐中", "餐后" };
	private static List<String[]> timeList;
	static {
		timeList = new ArrayList<String[]>();
		String[] time1 = { "12:00" };
		String[] time2 = { "8:00", "20:00" };
		String[] time3 = { "7:00", "12:00", "19:00" };
		String[] time4 = { "8:00", "12:00", "16:00", "20:00" };
		String[] time5 = { "7:00", "10:00", "12:00", "16:00", "19:00" };
		String[] time6 = { "7:00", "10:00", "12:00", "15:00", "17:00", "20:00" };
		// 测试用时间String[] time6 = { "16:35", "16:36", "16:37", "16:38", "16:39",
		// "16:40" };
		timeList.add(time1);
		timeList.add(time2);
		timeList.add(time3);
		timeList.add(time4);
		timeList.add(time5);
		timeList.add(time6);

	}

	/**
	 * 通过餐前餐后,频次得到用药时间
	 * 
	 * @param breakfast
	 * @param drugfrequency
	 * @return
	 */
	private static String[] getDrugTime(String breakfast, String drugfrequency) {
		int breakfastId = CommonUtil.getIdByArr(breakfastArr, breakfast);
		int drugfrequencyId = Integer.parseInt(drugfrequency);
		String[] timeArr = timeList.get(drugfrequencyId - 1);
		switch (breakfastId) {
		case 0:
			// 餐前
			for (int i = 0; i < timeArr.length; i++) {
				String[] eachTimeArr = timeArr[i].split(":");
				int h = Integer.parseInt(eachTimeArr[0]);
				int m = Integer.parseInt(eachTimeArr[1]);
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.HOUR_OF_DAY, h);
				calendar.set(Calendar.MINUTE, m);
				calendar.add(Calendar.MINUTE, -30);
				timeArr[i] = calendar.get(Calendar.HOUR_OF_DAY) + ":"
						+ calendar.get(Calendar.MINUTE);
			}
			break;
		case 2:
			// 餐后
			for (int i = 0; i < timeArr.length; i++) {
				String[] eachTimeArr = timeArr[i].split(":");
				int h = Integer.parseInt(eachTimeArr[0]);
				int m = Integer.parseInt(eachTimeArr[1]);
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.HOUR_OF_DAY, h);
				calendar.set(Calendar.MINUTE, m);
				calendar.add(Calendar.MINUTE, 30);
				timeArr[i] = calendar.get(Calendar.HOUR_OF_DAY) + ":"
						+ calendar.get(Calendar.MINUTE);
			}
			break;
		default:
			break;
		}

		return timeArr;
	}

	/**
	 * 生成血糖Alarm
	 * 
	 * @param time
	 *            时间 hh:mm
	 * @param week
	 *            星期list
	 * @return
	 */
	public Alarm getSugarAlarmByData(String time, List<String> week) {

		String[] timeArr = time.split(":");
		int hour = Integer.parseInt(timeArr[0]);
		int minutes = Integer.parseInt(timeArr[1]);
		DaysOfWeek dow = new DaysOfWeek(0);
		dow.set(0, false);
		dow.set(1, false);
		dow.set(2, false);
		dow.set(3, false);
		dow.set(4, false);
		dow.set(5, false);
		dow.set(6, false);
		for (int i = 0; i < week.size(); i++) {
			dow.set(Integer.parseInt(week.get(i)), true);
		}
		boolean enabled = true;
		boolean vibrate = true;

		return getInitAlarm(-1, enabled, hour, minutes, dow, vibrate, "测血糖啦");
	}

	/**
	 * 判断是否是闹钟类型
	 * 
	 * @param type
	 * @return
	 */
	public boolean isColock(int type) {
		if (type == 2) {
			return true;
		}
		return false;
	}

	/**
	 * 得到一个初始化的Alarm
	 * 
	 * @param id
	 * @param enabled
	 * @param hour
	 * @param minutes
	 * @param dw
	 * @param vibrate
	 * @param label
	 * @return
	 */
	public Alarm getInitAlarm(int id, boolean enabled, int hour, int minutes,
			DaysOfWeek dw, boolean vibrate, String label) {
		Alarm alarm = new Alarm();
		alarm.id = id; // 标识id唯一
		alarm.enabled = enabled;// 是否启用
		alarm.hour = hour; // 小时24时制
		alarm.minutes = minutes;// 分钟
		alarm.daysOfWeek = dw;// week对象
		alarm.vibrate = vibrate;// 是否震动
		alarm.label = label;// 提示
		alarm.alert = Uri.parse("content://settings/system/alarm_alert");// 铃声地址
		return alarm;
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if (arg0 == 999) {
			if (arg1 == MyConst.DRUG_RESULT) {
				ll_drug_all.setVisibility(View.VISIBLE);
				String drugData = arg2.getStringExtra("drugData");
				Log.e("plan", arg2.getStringExtra("drugData"));
				List<DrugPlanModel> drugPlan = HttpServer.gson.fromJson(
						drugData, new TypeToken<List<DrugPlanModel>>() {
						}.getType());

				plan.getDrugModelList().addAll(drugPlan);
				drugAdapter.notifyDataSetChanged();
				lv_health_plan_druglist.setAdapter(new DrugListAdpater(this,
						plan.getDrugModelList()));
			} else if (arg1 == MyConst.PLUS_RESULT) {
				ll_plus_all.setVisibility(View.VISIBLE);
				String drugData = arg2.getStringExtra("plusData");
				PlusModel plusData = HttpServer.gson.fromJson(drugData,
						PlusModel.class);
				plan.setPlusPressurePlanDetails(plusData);
				changePlus();
			}
		} else {
			if (arg1 == MyConst.DRUG_RESULT) {
				ll_drug_all.setVisibility(View.VISIBLE);
				String drugData = arg2.getStringExtra("drugData");
				Log.e("plan", arg2.getStringExtra("drugData"));
				List<DrugPlanModel> drugPlan = HttpServer.gson.fromJson(
						drugData, new TypeToken<List<DrugPlanModel>>() {
						}.getType());

				plan.getDrugModelList().set(arg0, drugPlan.get(0));
				drugAdapter.notifyDataSetChanged();
				lv_health_plan_druglist.setAdapter(new DrugListAdpater(this,
						plan.getDrugModelList()));
			}
		}

	}

	String beginTime = "";
	String endTime = "";
	DatePickerDialog.OnDateSetListener BeginDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 每次保存设置的日期

			beginCalendar.set(Calendar.YEAR, year);
			beginCalendar.set(Calendar.MONTH, monthOfYear);
			beginCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			et_sugar_begin_time.setText(+year + "/" + (monthOfYear + 1) + "/"
					+ dayOfMonth);
			et_sugar_end_time.setText(null);
		}
	};

	DatePickerDialog.OnDateSetListener EndDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			int byear = beginCalendar.get(Calendar.YEAR);
			int bmonth = beginCalendar.get(Calendar.MONTH);
			int bday = beginCalendar.get(Calendar.DAY_OF_MONTH);

			if ((byear * 365 + bmonth * 30 + bday) >= (year * 365 + monthOfYear
					* 30 + dayOfMonth)) {
				Toast.makeText(HealthPlanActivity.this, "结束时间不能小于起始时间", 0)
						.show();
				endCalendar = Calendar.getInstance();
				et_sugar_end_time.setText(null);

			} else {
				endCalendar.set(Calendar.YEAR, year);
				endCalendar.set(Calendar.MONTH, monthOfYear);
				endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				beginTime = byear + "/" + (bmonth + 1) + "/" + bday;
				endTime = year + "/" + (monthOfYear + 1) + "/" + dayOfMonth;

				et_sugar_begin_time.setText(beginTime);
				et_sugar_end_time.setText(endTime);

			}

		}
	};
	private String blood_pressure_note;

	public List<String> getMinDate() {
		List<String> dateList = new ArrayList<String>();
		try {

			String beginTime = plan.getDrugModelList().get(0)
					.getDrugbegintime();
			String endTime = plan.getDrugModelList().get(0).getDrugendtime();
			for (int i = 0; i < plan.getDrugModelList().size(); i++) {
				DrugPlanModel eachPlanModel = plan.getDrugModelList().get(i);
				String eachBegin = eachPlanModel.getDrugbegintime();
				String eachEnd = eachPlanModel.getDrugendtime();
				if (!CommonUtil.compareTime(endTime, eachEnd)) {
					endTime = eachEnd;
				}
				if (CommonUtil.compareTime(beginTime, eachBegin)) {
					beginTime = eachBegin;
				}

			}
			dateList.add(beginTime);
			dateList.add(endTime);
		} catch (Exception e) {
			dateList.add("");
			dateList.add("");
		}
		return dateList;
	}

	private void changePlus() {

		String plusBegintime = plan.getPlusPressurePlanDetails()
				.getPlan_begintime();
		String plusEndtime = plan.getPlusPressurePlanDetails()
				.getPlan_endtime();

		tv_plus_date.setText(plusBegintime.substring(5, 10) + "~"
				+ plusEndtime.substring(5, 10));
		String timestr = plan.getPlusPressurePlanDetails().getMesuretime();

		if (!TextUtils.isEmpty(plan.getPlusPressurePlanDetails().getNote())) {
			tv_plus_note.setText(plan.getPlusPressurePlanDetails().getNote());
		} else {
			tv_plus_note.setText("暂无");
		}
		String[] timearr = timestr.split("  ");
		tv_plus_frequency.setText(timearr.length + "次/天");
		tv_plus_timelist.setText(timestr);
		String weekStr = "";
		for (int i = 0; i < plan.getPlusPressurePlanDetails().getWeekList()
				.size(); i++) {
			weekStr = weekStr
					+ "  "
					+ MyConst.WEEK[Integer.parseInt(plan
							.getPlusPressurePlanDetails().getWeekList().get(i)) % 7];

		}
		tv_plus_week.setText(weekStr);

	}

}
